package com.ruoyi.deal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.deal.domain.HyDealCategory;
import com.ruoyi.common.core.page.PagePlus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.deal.bo.HyDealGoodsAddBo;
import com.ruoyi.deal.bo.HyDealGoodsEditBo;
import com.ruoyi.deal.bo.HyDealGoodsQueryBo;
import com.ruoyi.deal.domain.HyDealBrand;
import com.ruoyi.deal.domain.HyDealGoods;
import com.ruoyi.deal.mapper.HyDealGoodsMapper;
import com.ruoyi.deal.service.IHyDealBrandService;
import com.ruoyi.deal.service.IHyDealCategoryService;
import com.ruoyi.deal.service.IHyDealCollectService;
import com.ruoyi.deal.service.IHyDealGoodsService;
import com.ruoyi.deal.vo.HyDealCategoryVo;
import com.ruoyi.deal.vo.HyDealGoodsVo;
import com.ruoyi.system.domain.HyUser;
import com.ruoyi.system.service.IHyUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 商品管理Service业务层处理
 *
 * @author lixin
 * @date 2021-05-16
 */
@Service
public class HyDealGoodsServiceImpl extends ServicePlusImpl<HyDealGoodsMapper, HyDealGoods> implements IHyDealGoodsService {

	@Autowired
	private IHyDealCategoryService categoryService;

	@Autowired
	private IHyDealBrandService brandService;

	@Autowired
	private IHyUserService hyUserService;

	@Autowired
	private IHyDealCollectService collectService;

    @Override
    public HyDealGoodsVo queryById(Integer goodsId){
        HyDealGoods db = this.baseMapper.selectById(goodsId);
		db.setPicsArray(StrUtil.splitToArray(db.getPics(), Constants.SYMBOL_COMMA));
        return BeanUtil.toBean(db, HyDealGoodsVo.class);
    }

	/**
	 * 分页查询
	 * @param bo
	 * @return
	 */
	@Override
	public TableDataInfo<HyDealGoodsVo> queryPageList(HyDealGoodsQueryBo bo){
		PagePlus<HyDealGoods, HyDealGoodsVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), HyDealGoodsVo.class);

		// 返回视图数据处理
		List<HyDealGoodsVo> recordsVo = result.getRecordsVo();
		for (HyDealGoodsVo hyDealGoodsVo : recordsVo) {
			if (ObjectUtil.isNotNull(hyDealGoodsVo.getCategoryId())) {
				HyDealCategory category = categoryService.getById(hyDealGoodsVo.getCategoryId());
				hyDealGoodsVo.setCategoryName(category.getCategoryName());
			}
			if (ObjectUtil.isNotNull(hyDealGoodsVo.getBrandId())) {
				HyDealBrand brand = brandService.getById(hyDealGoodsVo.getBrandId());
				hyDealGoodsVo.setBrandName(brand.getBrandName());
			}
			HyUser hyUser = hyUserService.getById(hyDealGoodsVo.getUserId());
			hyDealGoodsVo.setUserName(hyUser.getNickName());
		}

		result.setRecordsVo(recordsVo);

		return PageUtils.buildDataInfo(result);
	}

	/**
	 * 不分页查询
	 * @param bo
	 * @return
	 */
    @Override
    public List<HyDealGoodsVo> queryList(HyDealGoodsQueryBo bo) {
		LambdaQueryWrapper<HyDealGoods> lqw = buildQueryWrapper(bo);
		lqw.orderByAsc(HyDealGoods::getUpdateTime, HyDealGoods::getCreateTime);
		return listVo(lqw, HyDealGoodsVo.class);
    }


	private LambdaQueryWrapper<HyDealGoods> buildQueryWrapper(HyDealGoodsQueryBo bo) {
		Map<String, Object> params = bo.getParams();
		LambdaQueryWrapper<HyDealGoods> lqw = Wrappers.lambdaQuery();
		lqw.like(StrUtil.isNotBlank(bo.getGoodsName()), HyDealGoods::getGoodsName, bo.getGoodsName());
		lqw.eq(bo.getUserId() != null, HyDealGoods::getUserId, bo.getUserId());
		lqw.eq(bo.getOriPrice() != null, HyDealGoods::getOriPrice, bo.getOriPrice());
		lqw.eq(bo.getPrice() != null, HyDealGoods::getPrice, bo.getPrice());
		lqw.eq(bo.getCategoryId() != null, HyDealGoods::getCategoryId, bo.getCategoryId());
		lqw.eq(bo.getBrandId() != null, HyDealGoods::getBrandId, bo.getBrandId());
		lqw.eq(bo.getSendType() != null, HyDealGoods::getSendType, bo.getSendType());
		lqw.eq(bo.getStatus() != null, HyDealGoods::getStatus, bo.getStatus());
		return lqw;
	}


    @Override
    public Boolean insertByAddBo(HyDealGoodsAddBo bo) {
        HyDealGoods add = BeanUtil.toBean(bo, HyDealGoods.class);
        if (StrUtil.isBlank(bo.getPic())) {
        	add.setPic(bo.getPicsArray()[0]);
		}
		String pics = StrUtil.join(Constants.SYMBOL_COMMA, bo.getPicsArray());
		add.setPics(pics);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(HyDealGoodsEditBo bo) {
        HyDealGoods update = BeanUtil.toBean(bo, HyDealGoods.class);
		String pics = StrUtil.join(Constants.SYMBOL_COMMA, update.getPicsArray());
		update.setPics(pics);
		validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(HyDealGoods entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(List<Integer> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

	@Override
	public HyUser queryUserByGoodsId(Integer goodsId) {
		HyDealGoods goods = baseMapper.selectById(goodsId);
		HyUser user = hyUserService.getOne(new QueryWrapper<HyUser>()
			.eq("user_id", goods.getUserId())
			.select("user_id", "nick_name", "email", "qqnumber", "sex", "avatar", "remark"));
		return user;
	}

	/**
	 * 商品发布
	 * @param bo
	 * @return
	 */
	@Override
	public Integer publish(HyDealGoodsAddBo bo) {

		if (queryCountByUserId(bo.getUserId()) > 50) {
			throw new CustomException("用户最多可以发布50个商品");
		}

		HyDealGoods add = BeanUtil.toBean(bo, HyDealGoods.class);
		add.setStatus(1);
		add.setPic(bo.getPicsArray()[0]);
		add.setPics(StrUtil.join(Constants.SYMBOL_COMMA, bo.getPicsArray()));

		validEntityBeforeSave(add);

		this.saveOrUpdate(add);

		return add.getGoodsId();
	}

	/**
	 * 商品删除
	 * @param goodsId
	 * @return
	 */
	@Override
	public Boolean deleteByGoodsId(Integer goodsId) {
		// 删除之前清空此商品的收藏表
		collectService.deleteByGoodsId(goodsId);
		return this.removeById(goodsId);
	}

	/**
	 * 商品下架
	 * @param goodsId
	 * @return
	 */
	@Override
	public Boolean soldOutByGoodsId(Integer goodsId) {
		HyDealGoods goods = this.getById(goodsId);
		goods.setStatus(0);
		return this.updateById(goods);
	}

	/**
	 * 商品上架
	 * @param goodsId
	 * @return
	 */
	@Override
	public Boolean putawayByGoodsId(Integer goodsId) {
		HyDealGoods goods = this.getById(goodsId);
		goods.setStatus(1);
		return this.updateById(goods);
	}

	/**
	 * 根据用户Id查询商品数量
	 * @param userId
	 * @return
	 */
	@Override
	public Integer queryCountByUserId(Integer userId) {
		LambdaQueryWrapper<HyDealGoods> lqw = Wrappers.lambdaQuery();
		lqw.eq(HyDealGoods::getUserId, userId);
		lqw.in(HyDealGoods::getStatus, 0, 1);

		return this.count(lqw);
	}

}
